/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-07-18 16:57:26
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-04-16 10:08:22
 * @FilePath: \ems_neutral_app\lib\pages\Mine\InfoManager\AccountManagerPage.dart
 * @Description: 账号管理——个人信息管理页
 */
import 'dart:io';

import 'package:ems_neutral_app/base/SilScaffold.dart';
import 'package:ems_neutral_app/common/widgets/cubitWidget/DividingLine.dart';
import 'package:ems_neutral_app/config/AppInfo.dart';
import 'package:ems_neutral_app/pages/Mine/AccountManager/EditNickNamePage.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/tools/SilTools.dart';

import '../../../base/SilAppBar.dart';
import '../../../utils/permission/PermissionUtils.dart';
import '../Language/LanguageController.dart';
import '../Language/SilLocalizations/SilLocalizations.dart';
import 'Controller/AccountManagerController.dart';
import 'EditCountryPage.dart';
import 'EditEmailPage.dart';
import 'EditPhonePage.dart';

class AccountManagerPage extends StatefulWidget {
  const AccountManagerPage({super.key});

  @override
  State<AccountManagerPage> createState() => _AccountManagerPageState();
}

class _AccountManagerPageState extends State<AccountManagerPage> {
  AccountManagerController _accountManagerController =
      Get.put(AccountManagerController());

  late ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();

    _accountManagerController.requestUserInfo(context: context);
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      sideMargin: 0,
      navBarHide: true,
      stateBarHide: true,
      backgroundColor: ColorUtils.hexColor('#191919'),
      body: Obx(() => mainWidget()),
    );
  }

  mainWidget() {
    return Container(
      color: ColorUtils.hexColor('#141414'),
      child: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(child: topInfoView()),

          /// 其他可修改项列表
          SliverToBoxAdapter(
            child: editListView(),
          ),

          /// 注销账号
          SliverToBoxAdapter(
            child: editListViewItem(
              title: LangOf(context)?.user?.logout,
              onTapFunc: () {
                _accountManagerController.requestDestroyAccount(
                    context: context,
                    successHandler: (p0) {
                      ARoute.pop(context);
                    });
              },
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              height: 20.w,
            ),
          ),
        ],
      ),
    );
  }

  topInfoView() {
    return Container(
      decoration: BoxDecoration(
          image: DecorationImage(
              image: AssetImage(AppInfo.stationType == '3'
                  ? 'imgs/set/set_bg_e3.png'
                  : 'imgs/set/set_bg.png'),
              fit: BoxFit.fitWidth,
              alignment: Alignment.topCenter)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            children: [
              topNavView(),
              Obx(() => accountAvatarView()),
            ],
          ),
        ],
      ),
    );
  }

  /// 顶部信息
  topNavView() {
    return Container(
      margin: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top, bottom: 30.w),
      child: SilAppBar(
        backgroundColor: Colors.transparent,
        leadingWidget: SilScaffoldButton.backButtonStatic(context),
        titleWidget: SilScaffoldButton.titleView(
            title: LangOf(context)?.user?.my_profile),
      ),
    );
  }

  /// 用户头像
  accountAvatarView() {
    return Container(
      margin: EdgeInsets.only(top: 100.w, bottom: 10.w),
      alignment: Alignment.center,
      child: Column(
        children: [
          SilEmptyButton(
            width: 110.w,
            height: 110.w,
            padding: EdgeInsets.all(4.w),
            borderColor: ColorUtils.hexColor('#606366'),
            borderWidth: 0.5.w,
            radius: 55.w,
            child: SilImage(
              _accountManagerController.avatar.value,
              width: 100.w,
              height: 100.w,
              radius: 50.w,
            ),
          ),
          SilButton(
            title: LangOf(context)?.user?.profile_photo,
            fontSize: 16.w,
            titleColor: ColorUtils.color_font_main,
            margin: EdgeInsets.only(top: 10.w),
            onTapFunc: showBottomSheet,
          )
        ],
      ),
    );
  }

  /// 可修改列表
  editListView() {
    return ListView(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: [
        editListViewItem(
          title: LangOf(context)?.user?.name,
          subTitle: _accountManagerController.nickName.value,
          onTapFunc: () => ARoute.gotoPage(context, EditNickNamePage()),
        ),
        editListViewItem(
            title: LangOf(context)?.user?.country,
            subTitle: _accountManagerController.countryName.value,
            onTapFunc: () => ARoute.gotoPage(context, EditCountryPage())),
        editListViewItem(
            title: LangOf(context)?.user?.phone,
            subTitle: _accountManagerController.userPhone.value,
            onTapFunc: () => ARoute.gotoPage(context, EditPhonePage())),
        editListViewItem(
          title: LangOf(context)?.user?.email,
          subTitle: _accountManagerController.email.value,
          onTapFunc: () => ARoute.gotoPage(context, EditEmailPage()),
        ),
      ],
    );
  }

  editListViewItem(
      {String? title, String? subTitle, void Function()? onTapFunc}) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SilEmptyButton(
          onTapFunc: onTapFunc,
          useConstrained: true,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 25.w),
          child: Row(
            children: [
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SilText(
                    title,
                    fontSize: 16.sp,
                    color: ColorUtils.color_font_main,
                    margin: EdgeInsets.only(
                        bottom: (!SilTools.stringIsEmpty(subTitle)) ? 8.w : 0),
                    maxLines: 0,
                  ),
                  if (!SilTools.stringIsEmpty(subTitle))
                    SilText(
                      subTitle,
                      fontSize: 12.sp,
                      color: ColorUtils.color_font_minor,
                      maxLines: 0,
                    ),
                ],
              )),
              SilImage(
                'imgs/personal/personal_fh.png',
                height: 27.w,
                width: 27.w,
              )
            ],
          ),
        ),
        DividingLine(
          margin: EdgeInsets.only(left: 15.w, right: 15.w),
        )
      ],
    );
  }

  showBottomSheet() {
    LanguageController languageController = LanguageController();
    bool isPromptEnglish = languageController.isPromptEnglish();
    List<String> items =
        isPromptEnglish ? ['Camera', 'Photo Album'] : ['相机', '相册'];
    SilBottomSheet.show(
        context: context,
        child: SilBottomSheetWidget(
          itemList: items,
          tapSureSeletedFunc: (selectedIndex) async {
            if (selectedIndex == 0) {
              // 相机
              bool value = await PermissionUtils.permission_camera();
              if (value == false) return;
              _onToCamera();
              Navigator.pop(context);
            } else {
              // 相册
              bool value = await PermissionUtils.permission_photo();
              if (value == false) return;
              _onToAlbum();
              Navigator.pop(context);
            }
          },
          cancelTitle: isPromptEnglish ? 'cancle' : '取消',
        ));
  }

  /// 拍摄照片
  Future<void> _onToCamera() async {
    final image = await _picker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    handlerImage(image.path);
  }

  /// 从相册选取
  Future<void> _onToAlbum() async {
    final image = await _picker.pickImage(source: ImageSource.gallery);
    if (image == null) return;
    handlerImage(image.path);
  }

  /// 处理图片：压缩、裁剪等
  handlerImage(String path) async {
    // 压缩图片
    File file = await FlutterNativeImage.compressImage(path,
        quality: 50, percentage: 50);

    String imgPath = file.path;

    if (!SilTools.stringIsEmpty(imgPath)) {
      _accountManagerController.requestSettingAvatar(
          context: context, filePath: imgPath);
    }
  }
}
